window.__apiHost = 'http://192.168.0.33:8888/';//'http://api.qixinwen.com/'
console.log('445444')
var hrefA="/admin.html#"
 localStorage.setItem('dev',0)
if (localStorage.dev == '1') {
	__apiHost = 'http://192.168.0.123:9005';
	 hrefA="/admin.html#"
} else {
	__apiHost = 'http://bsy.5niu.top/';
	 hrefA="/cuser/admin.html#"
}
//import Welcome from '../page/welcome.js'
var apiHost = './api.php';
window.log = function() {
	var al = arguments;
	console.log(...al)
}
window.__copy = function (data) {
	var copy = JSON.parse(JSON.stringify(data));
	return copy;
}
window.__ss = function (k,v) {
	if (k) {
		sessionStorage.setItem(k,v);
	}
}
window.__ls = function (k,v) {
	if (k) {
		localStorage.setItem(k,v);
	}
}
window.__gss = function (k) {
	if (k) return sessionStorage.getItem(k);
	return sessionStorage
}
window.__gls = function (k) {
	if (k) return localStorage.getItem(k);
	return localStorage
}
window.__url = function (k) {
	return apiHost;
}
window.__app = {};
window.__router = {};

window.ajax = function(config) {
	var isString = function(val) {
		return typeof val === 'string';
	}
	var isObject = function(val) {
		return val !== null && typeof val === 'object';
	}
	var isFormData = function(val) {
		return(typeof FormData !== 'undefined') && (val instanceof FormData);
	}
	var isUndefined = function(val) {
		return typeof val === 'undefined';
	}
	var isArray = function(val) {
		return toString.call(val) === '[object Array]';
	}
	//var trim        =  function(str) { return str.replace(/^\s*/, '').replace(/\s*$/, '');}
	var createError = function(message, config, code, request, response) {
		var error = new Error(message);
		error.config = config;
		if(code) {
			error.code = code;
		}
		error.request = request;
		error.response = response;
		return error;
	};
	var settle = function(resolve, reject, response) {
		var validateStatus = function(status) {
			return status >= 200 && status < 300;
		}
		if(!response.status || validateStatus(response.status)) {
			//console.log('settle',response);
			if (response && (response.code === 1003)){
				reject(response);
				console.log('ajax code === 1003 to /login')
				if (__router.push) __router.push('/login');
				return;
			}
			if (response.code === 200) {
				if (config.url) {
					let u = config.url;
					//console.log(u);
					if (u == 'admin/get_captcha') {
						
					}else {
						if (response.data.token) {
							__ls('token',response.data.token);
						}
						window.__timeOut = setTimeout(function (){
							// __app.setLogin(true);
						},20)
					}
				}
			}
			
			if (isObject(response)) {
				let res = response;
				if (res.data) {
					let d = res.data;
					if (d.list && (isObject(d.list) || (isArray(d.list)))) {
						let current_page = d.current_page;
						let total_page   = d.total_page;
						let limit = d.limit;
						// let list  = d.list;
						let r = {};
						for (let k in response) r[k] = response[k];
						r.current_page = current_page;
						r.total_page = total_page;
						r.limit = limit;
						r._data = r.data;
						r.data = r.data;
						res = r;
					}
				}
				//console.log('res:',res);
				resolve(res);
			} else {
				resolve(response);
			}
			
		} else {
			reject(createError('Request failed with status code ' + response.status,
				response.config, null, response.request, response));
		}
	};
	var forEach = function(obj, fn) {
		if(obj === null || typeof obj === 'undefined') {
			return;
		}
		if(typeof obj !== 'object') {
			obj = [obj];
		}
		if(isArray(obj)) {
			for(var i = 0, l = obj.length; i < l; i++) {
				fn.call(null, obj[i], i, obj);
			}
		} else {
			for(var key in obj) {
				if(Object.prototype.hasOwnProperty.call(obj, key)) {
					fn.call(null, obj[key], key, obj);
				}
			}
		}
	}

	if(!config.method) config.method = 'GET';

	return new Promise(function dispatchXhrRequest(resolve, reject) {
		var requestData = config.data;
		var requestHeaders = config.headers || {};
		var qss = '';
		if(isFormData(requestData)) {
			delete requestHeaders['Content-Type'];
		} else {
			if(isObject(requestData)) {
				requestHeaders['Content-Type'] = "application/json;charset=UTF-8";
				let us = config.url;
				let has = false;
				if (isString(us)) {
					let usa = us.indexOf('?');
					if (usa != -1) has = true
				}
				for (var k in requestData) {
					if (k == 'undefined') continue;
					if ((qss.length > 2) ||  has) qss += '&';
					qss = qss + k + '=' + requestData[k];
					//console.log(qss,k,requestData[k])
				}
				requestData = JSON.stringify(requestData);
				
			}
		}
		var request = new XMLHttpRequest();
		if(config.auth) {
			var username = config.auth.username || '';
			var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
			requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
		}
		var fullPath = config.url || (isString(config) ? config : '/');
		if (fullPath.indexOf('http') === -1) fullPath = __apiHost + fullPath;
		if (config.method == 'get' || config.method == 'GET') {
			let append = (fullPath.indexOf('?') === -1);
			//console.log(append,qss)
			fullPath = fullPath + (append ? '?' : '') + qss;
		}
		request.open(config.method.toUpperCase(), fullPath, true);
		request.timeout = config.timeout || 20000;
		request.onreadystatechange = function handleLoad() {
			if(!request || request.readyState !== 4) {
				return;
			}
			var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
			responseData = request.responseText;
			var response = {};
			let str = responseData;
			try{
				// console.log('responseData',responseData);
				if ((str[0] == '{')) {
					
				} else {
					let i = str.indexOf('{"');
					let l = str.length || 0;
					if (i && l) str = str.substr(i,l-i);
				}
				response = eval('(' + str + ')');
			}catch(err){
				console.log(err)
				console.log('responseText',str)
			}
			
			var info = {
				status: request.status,
				statusText: request.statusText,
				config: config,
				request: request
			};
			response._requestInfo = info;
			settle(resolve, reject, response);
			request = null;
		};
		request.onabort = function handleAbort() {
			if(!request) {
				return;
			}
			reject(createError('Request aborted', config, 'ECONNABORTED', request));
			request = null;
		};

		request.onerror = function handleError() {
			reject(createError('Network Error', config, null, request));
			request = null;
		};

		request.ontimeout = function handleTimeout() {
			var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';
			if(config.timeoutErrorMessage) {
				timeoutErrorMessage = config.timeoutErrorMessage;
			}
			reject(createError(timeoutErrorMessage, config, 'ECONNABORTED', request));
			request = null;
		};

		if('setRequestHeader' in request) {
			forEach(requestHeaders, function setRequestHeader(val, key) {
				if(typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
					delete requestHeaders[key];
				} else {
					request.setRequestHeader(key, val);
				}
			});
		}

		if(!isUndefined(config.withCredentials)) {
			request.withCredentials = !!config.withCredentials;
		}
		if(config.responseType) {
			try {
				request.responseType = config.responseType;
			} catch(e) {
				if(config.responseType !== 'json') {
					throw e;
				}
			}
		}
		if(typeof config.onDownloadProgress === 'function') {
			request.addEventListener('progress', config.onDownloadProgress);
		}
		if(typeof config.onUploadProgress === 'function' && request.upload) {
			request.upload.addEventListener('progress', config.onUploadProgress);
		}
		if(!requestData) {
			requestData = null;
		}
		request.send(requestData);
	});
};
console.log('...al')
var __api = {
	login: 'http://192.168.0.123:9005/admin/ajax/login',
	article:'http://192.168.0.123:9005/admin/article/article/list?&page=1&limit=15',
}
if (!window.routes) window.routes = [];

var __widget = [
	{
		name: 'App',
		template: `
		<div class="wh100 pr ofh trs2" name="main" :style="{'opacity': opacity}">
			<transition name="slide-fade">
				<router-view></router-view>
			</transition >
	  	</div>`,
		data: function () {
			return {
				opacity: 0,
				setting: false,
				isAdmin: false,
			}
		},
		methods: {
			openSetting(){this.setting = true;},
			getList() {
				let v = this;
				let data = {};
				__post(__url('components')).then(r => {
					let l = r.data;
				})
			},
			doLogin() {
				let v = this;
				let fd = new FormData();
				fd.append('username','ysh');
				fd.append('password','123456');
				__post({url:__api.login,data:fd}).then(r => {
					let l = r.data;
				}).catch(e =>{ console.log(e);})
			},
		},
		created: function () {
			let v = this;
			v.opacity = 1;
			// v.doLogin('menu');
		},
	},
]
if (!window.widgets) window.widgets = [];
for (let n in __widget) window.widgets.push(__widget[n]);


const route = [
{
	path: '/',
	name: 'Welcome',
	component: () => import('../page/welcome.js?v='+Date.now()),
},
{
	path: '/firstaid',
	name: 'Firstaid',
	component: () => import('../page/firstaid.js?v='+Date.now()),
},
{
	path: '/dordinary',
	name: 'D_ordinary',
	component: () => import('../page/details_ordinary.js?v='+Date.now()),
},
{
	path: '/personinfo',
	name: 'Personinfo',
	component: () => import('../page/personinfo.js?v='+Date.now()),
},
{
	path: '/changeInfo',
	name: 'changeInfo',
	component: () => import('../page/changeInfo.js?v='+Date.now()),
},
]

function _start() {
	// 3. 注册组件
	for (let i = 0; i < widgets.length; i++) {Vue.component(widgets[i].name, widgets[i]);};
	for (let i = 0; i < route.length; i++) routes.push(route[i])
	__router = new VueRouter({
		routes: routes
	})
	__router.beforeEach((to, from, next) => {
		log('beforeEach to',to)
		next();
	})
	// 4. 创建和挂载根实例。
	__app = new Vue({
		router: __router,
		data: {
			opacity: 0,
		},
		methods: {
		},
		mounted: function () {
		}
	}).$mount('#app_dom')
	log('start... ');
	{
		let str = location.search.substr(1);
		let arr = str.split("&");
		if(arr.length > 1){
			let arr1 = arr[0].split("=");
			
			console.log('start search',str);
			console.log('start token',arr1[1]);
			if (arr1[1] && !localStorage.token) localStorage.setItem('token',arr1[1])
		}
	}
}

window.addEventListener('load',_start,false);
log('44444')
var __id = 1;
function __getid () {
	let s = '' + Date.now() + Math.random() + __id;
	s = s.replace(".", "_");
	__id++;
	return s;
}
function __post (url, data) {
	// console.log(url)
	var isFormData = function(val) {
		return(typeof FormData !== 'undefined') && (val instanceof FormData);
	}
	if (typeof url == 'object') {
		let t = __copy(url);
		url = t.url;
		data = t.data;
	}
	let headers = {
		'content-type': 'application/json',
	}
	if(isFormData(data)) {
		headers['content-type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
	}
	return fetch(url, {
		body: JSON.stringify(data),
		cache: 'no-cache',
		headers: headers,
		method: 'POST',
		// mode: 'no-cors',
		mode: 'cors',
	//}).then(response => response.json()) // parses response to JSON
	}).then( response => {
		return response
	}).catch ( err => {
		console.log(err);
		return err
	})
}
window.__message = function (context, duration, className) {
	
	if ((typeof duration == 'string')) {
		className = duration;
		duration = 5000;
	} else {
		if (!duration) duration = 5000;
	}
	if (!window.__message_list) window.__message_list = [];
	if ((typeof className != 'string')) className = '';
	let dc = function (label, attr) {
	if (!label || (typeof label != 'string')) label = 'div';
		let el = document.createElement(label);
		if (attr && (typeof attr == 'object')) {
			for (let k in attr) {
				let v = attr[k];
				if ((typeof v[0] == 'string') && (typeof v[0] == 'string')) el.setAttribute(v[0],v[1]);
			}
		}
		return el;
	}
	let bcn = '__message_box';
	let box = document.querySelector('.' + bcn);
	if (!box) {
		box = dc('div',[['name',bcn],['class',bcn + ' t0 fs12 w100 z9']])
		box.style.top = '100px'
		document.body.appendChild(box);
	}
	
	let id  = 'm-' + Date.now();
	let msg = dc('div',[['id',id],['class','msg-item-box pf trs3 t0 l0 r0 a z9']]);
	
	let con = dc('div',[['name',id],['class','msg-item-content pr flex center c666']]);
	let content = dc('div',[['name','msg_text'],['class','text-content pa disi bgf msgshadow br2 pdl15 pdr40 pdtb10 sp1 lh20 bbx trs2 ' + className]]);
	let txt = dc('div',[['name','text'],['class','pr wh100']]);
	let ico = dc('div',[['name','close'],['class','pa t0 r0 w30 h40 hovopa1 opa8 btn sen']]);
	let margin = 30;
	let height = 40;
	let items = document.querySelectorAll('.msg-item-box');
	if (items && items.length) {
		let last = items[items.length - 1];
		let ctx  = last.querySelector('.text-content');
		if (ctx) {
			let atop = parseInt(last.getAttribute('top')) || margin;
			height = (ctx.clientHeight) || height;
			margin = atop + height + 10;
		}
	}
	msg.setAttribute('top',margin)
	if(!window.__transferIndex ) window.__transferIndex = 1;
	msg.style.zIndex = (__transferIndex + 10);
	msg.style.top = '' + (margin - 30) + 'px';
	
	txt.innerHTML = context;
	ico.innerHTML = '<i class="fs10 fa fa-close"></i>';
	content.appendChild(txt)
	content.appendChild(ico)
	con.appendChild(content);
	msg.appendChild(con);
	box.appendChild(msg);
	
	let out = setTimeout(function () {
		msg.style.top = '' + margin + 'px';
		msg.style.opacity = 1;
	},20)
	let updateTop = function () {
		let box = document.querySelector('.__message_box');
		let list = box.querySelectorAll('.msg-item-box');
		if (!list.length) return;
		let marginTop = 30;
		for (let k = 0; k < list.length; k++) {
			let me = list[k];
			if (1) {
				me.style.top = '' + marginTop + 'px';
				me.setAttribute('top',marginTop);
				let ctx  = me.querySelector('.text-content');
				let meHeight = 40;
				if (ctx) { meHeight = (ctx.clientHeight) || meHeight; }
				marginTop = marginTop + meHeight + 10;
			}
		}
	}
	let close = function () {
		let currMargin= parseInt(msg.style.top) || "10px";
		msg.style.top = '' + (currMargin - 20) + 'px';
		msg.style.opacity = 0;
		setTimeout(function () {
			let me = box.querySelector('#' + id);
			if (me) box.removeChild(me);
			updateTop();
			for (let i = 0 ; i < __message_list.length; i++) {
				if (__message_list[i].id == msg.id) __message_list.splice(i,1);
			}
		},200)
	}
	ico.addEventListener('click', close, false);
	out = setTimeout(function () {
		ico.removeEventListener('click', close, false);
		msg.close();
	},duration)
	
	msg.timeout = out;
	msg.close   = close;
	msg.updateTop = updateTop;
	__message_list.push(msg)
	return msg;
}
window.__confirm = function (context,wait) {
	if (!wait || (typeof wait != 'number')) wait = 20000;
	return new Promise(function __cfm(resolve, reject){
		let dc = function (label, attr) {
		if (!label || (typeof label != 'string')) label = 'div';
			let el = document.createElement(label);
			if (attr && (typeof attr == 'object')) {
				for (let k in attr) {
					let v = attr[k];
					if ((typeof v[0] == 'string') && (typeof v[0] == 'string')) el.setAttribute(v[0],v[1]);
				}
			}
			return el;
		}
		let bcn = '__confirm_box';
		let box = document.querySelector('.' + bcn);
		if (!box) {
			box = dc('div',[['name',bcn],['class',bcn + ' t0 fs12 w100']])
			box.style.top = '0px'
			document.body.appendChild(box);
		}
		
		let id  = 'm-' + Date.now();
		let cfm = dc('div',[['id',id],['class','cfm-item-box a pf trs3 t0 l0 r0 b0 flex alc center']]);
		
		let mask = dc('div',[['name',id],['class','cfm-item-content pa wh100 bg03 flex alc center c666']]);
		let content = dc('div',[['name','cfm_text'],['class','text-content pr bgf msgshadow br2 pd015 pdtb10 sp1 lh20 bbx trs2 marb5']]);
		let txt = dc('div',[['name','text'],['class','pr w100 pdr40 pdtb10 txt']]);
		let ico = dc('div',[['name','close'],['class','pa t10 r10 w30 h30 hovopa1 opa8 btn sen bg05']]);
		let okb = dc('div',[['name','ok'],['class','h30 flex alc right mart5']]);
		let btn = dc('div',[['name','btn'],['class','pd05 btn h25 w40 bgcr opa8 hovopa1 trs2 cfff']]);
	
		cfm.style.zIndex = (__transferIndex + 10);
		
		txt.innerHTML = context;
		ico.innerHTML = '<i class="fs10 fa fa-close"></i>';
		btn.innerHTML = '<span >确定</span>';
		content.appendChild(txt)
		content.appendChild(ico)
		content.appendChild(okb)
		okb.appendChild(btn)
		cfm.appendChild(mask);
		cfm.appendChild(content);
		box.appendChild(cfm);

		let close = function () {
			ico.removeEventListener('click', close, false);
			btn.removeEventListener('click', ok, false);
			cfm.style.opacity = 0;
			setTimeout(function () {
				let me = box.querySelector('#' + id);
				if (me) box.removeChild(me);
				reject('a');
			},200)
		}
		let ok = function () {
			ico.removeEventListener('click', close, false);
			btn.removeEventListener('click', ok, false);
			cfm.style.opacity = 0;
			setTimeout(function () {
				let me = box.querySelector('#' + id);
				if (me) box.removeChild(me);
				resolve('a');
			},200)
		}
		ico.addEventListener('click', close, false);
		btn.addEventListener('click', ok, false);
		cfm.close   = close;
		setTimeout(function () {
			cfm.style.opacity = 1;
		},20)
		
		setTimeout(function () {
			let me = box.querySelector('#' + id);
			if (me) box.removeChild(me);
			reject('b');
		},wait)
	})
	return cfm;
}
window.__msg = function (r,data) {
	if (r.count === 1) {
		__message('success','cg');
	} else {
		__message(data.action + ' failed!',10000,'cr');
	}
}
